package com.atguigu.network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class Demo06UDPServer {

    public static void main(String[] args) throws IOException {

        // 1、创建代表 UDP 连接的 Socket 对象
        DatagramSocket datagramSocket = new DatagramSocket(9999);

        // 2、在永久循环中接收客户端发送的数据
        while (true) {
            // 3、封装数据包对象
            byte[] bytes = new byte[1024];

            DatagramPacket datagramPacket = new DatagramPacket(bytes, 0, bytes.length);

            // 4、调用 Socket 对象的方法接收数据
            datagramSocket.receive(datagramPacket);

            // 5、拆封数据
            byte[] data = datagramPacket.getData();
            String receivedData = new String(data, 0, datagramPacket.getLength());
            System.out.println("receivedData = " + receivedData);
        }
    }

}
